import Api from '../../utils/api.js';
import prompt from '../../utils/prompt.js';

const app = getApp();

// pages/message/message.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    noMoreData: false, // 是否无更多数据
    loading: false,
    messageList: [],
    current: 1,
    size: 20,
    writing: false,
    isManager: false,
    message: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isManager: app.globalData.userInfo.userType === '1',
      writing: app.globalData.userInfo.userType !== '1'
    }, () => {
      if (this.data.isManager) {
        this.getMessages();
      }
    });
  },

  /* --================数据请求================-- */
  // 查询留言数据
  async getMessages () {
    this.setData({ loading: true });
    const res = await Api.getmessages({
      current: this.data.current,
      size: this.data.size,
      sessionKey: app.globalData.sessionKey
    }, {
      loading: this.data.messageList.length === 0
    });
    if (res.retCode === '0') {
      const messages = [...this.data.messageList, ...res.message];
      this.setData({ messageList: messages });
    } else if (res.retCode === '2020') {
      this.setData({ noMoreData: true });
    }
    this.setData({ loading: false });
  },
  // 发布留言
  async postMessage () {
    const pro = await prompt.showModal('确定发布留言吗？', {
      showCancel: true
    });
    if (pro.confirm) {
      const res = await Api.postMessage({
        content: this.data.message
      }, app.globalData.sessionKey);
      if (res && res.retCode === '0') {
        prompt.showToast('留言成功', 'success');
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
        // this.setData({ writing: false, message: '' }, () => {
        //   this.getMessages();
        // });
      }
    }
  },

  /* --================事件处理================-- */
  // 编辑按钮点击处理
  handleEditTap () {
    if (this.data.writing) {
      if (this.data.message) {
        this.postMessage();
      } else {
        prompt.showToast('请输入留言');
      }
    } else {
      this.setData({ writing: true });
    }
  },
  // 文本输入事件
  handleInput (e) {
    const param = {};
    param[e.currentTarget.dataset.state] = e.detail.value;
    this.setData(param);
  },
  // 提交 处理
  bindconfirm () {
    if (this.data.message) {
      this.postMessage();
    }
  },
  // 遮罩点击
  handleMaskTap () {
    if (this.data.isManager) {
      this.setData({ writing: false });
    }
  },
  // 下拉到底部
  handleToLower () {
    if (!this.data.noMoreData) {
      this.setData({
        current: this.data.current + 1
      }, () => {
        this.getMessages();
      });
    }
  }
});